/*
 * 
 * Thread that handles image queues, saves them to the database
 */

package database;

import java.net.URI;
import java.util.LinkedList;

public class ImageHandler extends Thread 
{
	private static ImageHandler mInstance;
	private LinkedList <ImageRecord> mImageQueue;
	
	private volatile boolean mRunning = true;
	
	private volatile int totalImages = 0;

	private ImageHandler()
	{	
		mImageQueue = new LinkedList<ImageRecord>();
	}
	
	public static ImageHandler getInstance()
	{
		if (mInstance != null)
			return mInstance;
		else
		{
			mInstance = new ImageHandler();
			return mInstance;
		}
	}
	
	public int getQueueSize()
	{
		synchronized ( mImageQueue )
		{
			return mImageQueue.size();
		}
	}
	
	/* Stops handler */
	public void stopProcess()
	{
		mRunning = false;
		
		synchronized ( this )
		{
			this.notify();
		}
	}
	
	public int getTotalImages()
	{
		return totalImages;
	}
	
	/* Add images to queue */
	public boolean addImage( URI pageURL, URI imageURL, String pageTitle, String mimetype, int size, String sitelink )
	{
		ImageRecord image = new ImageRecord( pageURL, imageURL, pageTitle, mimetype, size, sitelink );
		totalImages++;
		synchronized ( mImageQueue )
		{
			return mImageQueue.add( image );
		}
	}
	
	/* handles image queue and save all of them in a single insert */
	public void handleImageQueue()
	{
		SqlManager.getInstance().handleImageQueue( mImageQueue );
	}
	
	public void run ()
	{
		Thread.currentThread().setName("IMAGE HANDLER");
		while ( mRunning )
		{
			
			handleImageQueue();
			
			try 
			{
				synchronized (this)
				{
					/* runs every 10 seconds */
					this.wait(10000);
				}
			} 
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
		}
	}
}
